﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Filtry.Data;
using Filtry.Utilities;

namespace Filtry.Logic
{
    public static class ImageQuality
    {
        /// <summary>
        /// Calculates image SNR
        /// </summary>
        /// <returns>SNR value</returns>
        public static double CalculateSNR(GrayscaleImage originalImg, GrayscaleImage filteredImg)
        {
            //double nmse = NMSE(originalImg, filteredImg);
            //return -10 * Math.Log10(nmse);

            var pixels = originalImg.GetAllPixels();
            var average = pixels.Average(b => b);
            var length = pixels.LongLength;
            var variancja = pixels.Sum(pixel => Math.Pow(pixel - average, 2)/length);
            var filteredPixels = filteredImg.GetAllPixels();
            var mse = 0.0;
            for (int i = 0; i < pixels.LongLength; i++)
            {
                mse += Math.Pow(pixels[i] - filteredPixels[i], 2)/length;
            }
            return 10 * Math.Log10(variancja / mse);
        }

        private static double NMSE(GrayscaleImage originalImg, GrayscaleImage filteredImg)
        {
            return MSE(originalImg, filteredImg, Metric.Manhattan) / originalImg.CalculateVariance();
        }


        private static double MSE(GrayscaleImage originalImg, GrayscaleImage filteredImg, Metric metric)
        {
            var originalPixels = originalImg.GetAllPixels();
            var filteredPixels = filteredImg.GetAllPixels();

            var distance = Tools.CalculateDistance(originalPixels, filteredPixels, metric, ImgType.Gray);
            var d2 = distance.Sum(b => b * b);
            return d2 / (double)distance.Length;

        }

    }


}
